package com.base.common.utils.matisse;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.base.common.R;
import com.base.common.viewmodel.BaseRxObserver;
import com.base.common.utils.IOUtils;
import com.base.common.utils.LogUtil;
import com.base.common.permission.PermissionUtils;
import com.base.common.utils.UIUtils;
import com.base.common.viewmodel.RxSchedulerTransformer;
import com.lxj.matisse.CaptureMode;
import com.lxj.matisse.Matisse;
import com.lxj.matisse.MimeType;
import com.lxj.matisse.SelectionCreator;
import com.lxj.matisse.filter.Filter;
import com.lxj.matisse.listener.ImageEditUtils;

import java.io.File;
import java.util.List;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import me.kareluo.imaging.IMGEditActivity;

import static android.app.Activity.RESULT_OK;


/**
 * Matisse
 * .from(mActivity)
 * //选择视频和图片
 * .choose(MimeType.ofAll())
 * //选择图片
 * .choose(MimeType.ofImage())
 * //选择视频
 * .choose(MimeType.ofVideo())
 * //自定义选择选择的类型
 * .choose(MimeType.of(MimeType.JPEG,MimeType.AVI))
 * //是否只显示选择的类型的缩略图，就不会把所有图片视频都放在一起，而是需要什么展示什么
 * .showSingleMediaType(true)
 * //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
 * .capture(true)
 * .captureStrategy(new CaptureStrategy(true,"PhotoPicker"))
 * //有序选择图片 123456...
 * .countable(true)
 * //最大选择数量为9
 * .maxSelectable(9)
 * //选择方向
 * .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
 * //界面中缩略图的质量
 * .thumbnailScale(0.8f)
 * //蓝色主题
 * .theme(R.style.Matisse_Zhihu)
 * //黑色主题
 * .theme(R.style.Matisse_Dracula)
 * //Glide加载方式
 * .imageEngine(new GlideEngine())
 * //Picasso加载方式
 * .imageEngine(new PicassoEngine())
 * //请求码
 * .forResult(REQUEST_CODE_CHOOSE);
 */


/**
 * 图片选择器
 */
public class MatisseUtils {


    private static final int REQUEST_CODE_CHOOSE = 0x9321;
    private static final int REQ_IMAGE_EDIT = 0x9333;

    private boolean isCropImage = false;//是否剪切？  未封装完毕

    private static ObservableEmitter<String> emitterPrivate = null;
    private static File mImageFile;//缓存编辑后的图片

    private boolean isSelectedGif = true;//是否可选动图


    public static MatisseUtils of() {
        return new MatisseUtils();
    }

    public MatisseUtils setSelectedGif(boolean selectedGif) {
        isSelectedGif = selectedGif;
        return this;
    }

    /**
     * @param activity
     * @param maxCount 最大选择图片数量
     * @param isCrop   是否剪切
     * @return
     */
    public Observable<String> observable(final FragmentActivity activity, int maxCount, int videoCount, boolean... isCrop) {
        if (isCrop.length > 0) isCropImage = isCrop[0];
        else isCropImage = false;

        setImageEditer();
        PermissionUtils.initCAMERAPermission(activity).subscribe(new BaseRxObserver<Boolean>() {
            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    selectPic(Matisse.from(activity), maxCount, videoCount);
                }
            }
        });

        return observables();
    }

    public Observable<String> observable(final Fragment fragment, int maxCount, int videoCount, boolean... isCrop) {
        if (isCrop.length > 0) isCropImage = isCrop[0];
        else isCropImage = false;
        setImageEditer();
        PermissionUtils.initCAMERAPermission(fragment).subscribe(new BaseRxObserver<Boolean>() {
            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    selectPic(Matisse.from(fragment), maxCount, videoCount);
                }
            }
        });

        return observables();
    }


    private static Observable<String> observables() {
        return Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitterPrivate = emitter;
            }
        }).compose(new RxSchedulerTransformer<String>());
    }


    private void selectPic(@NonNull Matisse matisse, int maxCount, int videoCount) {
        UIUtils.runInMainThread(new Runnable() {
            @Override
            public void run() {
                SelectionCreator selectionCreator;
                //自定义选择选择的类型
//               matisse .choose(MimeType.of(MimeType.JPEG,MimeType.AVI))
                if (maxCount == 0 && videoCount > 0) {
                    selectionCreator = matisse.choose(MimeType.ofVideo()).maxSelectable(videoCount).capture(true, CaptureMode.Video);//只选择视频
                } else if (maxCount > 0 && videoCount == 0) {
                    selectionCreator = matisse.choose(isSelectedGif ? MimeType.ofImage() : MimeType.onlyImage()).maxSelectable(maxCount).capture(true, CaptureMode.Image);//只选择图片
                } else if (maxCount > 0 && videoCount > 0) {
                    selectionCreator = matisse.choose(MimeType.ofAll()).maxSelectablePerMediaType(maxCount, videoCount).capture(true, CaptureMode.All);//选择视频和图片
                } else {
                    return;
                }


                //是否只显示选择的类型的缩略图，就不会把所有图片视频都放在一起，而是需要什么展示什么
                selectionCreator.showSingleMediaType(true)
//                .capture(true)  //是否显示拍摄按钮，默认不显示
                        //.capture(true, CaptureMode.All)//是否显示拍摄按钮，可以同时拍视频和图片
//                .jumpCapture()//直接跳拍摄，默认可以同时拍摄照片和视频
                        //.jumpCapture(CaptureMode.Image)//只拍照片
                        //.jumpCapture(CaptureMode.Video)//只拍视频
//                        .captureStrategy(new CaptureStrategy(true, UIUtils.getPackageName() + ".fileProvider"))
                        .isCrop(isCropImage) //开启裁剪
//        R.style.Matisse_Zhihu (light mode)
//        R.style.Matisse_Dracula (dark mode)
                        .theme(R.style.Matisse_Zhihu)
                        //有序选择图片 123456..
                        .countable(true)
//                .maxSelectable(maxCount)
//                .maxSelectablePerMediaType(maxCount, videoCount)

                        .addFilter(new GifSizeFilter(0, 0, 5 * Filter.K * Filter.K))
                        .addFilter(new VideoSizeFilter(15 * Filter.K * Filter.K))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.5f)
                        .imageEngine(new GlideImageEngine())
                        .forResult(REQUEST_CODE_CHOOSE);
            }
        });
    }


    private static void setImageEditer() {
        //设置图片编辑
        ImageEditUtils.getInstance().setImageEditInterface(new ImageEditUtils.ImageEditInterface() {
            @Override
            public String editString() {
                return "编辑";
            }

            @Override
            public void editOnclickListener(View view, Uri image) {

                mImageFile = new File(IOUtils.getPicturesPath(), UUID.randomUUID().toString() + ".jpg");
                //弹出图片编辑
                Intent intent = new Intent(view.getContext(), IMGEditActivity.class);
                intent.putExtra(IMGEditActivity.EXTRA_IMAGE_URI, image);
                intent.putExtra(IMGEditActivity.EXTRA_IMAGE_SAVE_PATH, mImageFile.getAbsolutePath());
                ((Activity) view.getContext()).startActivityForResult(intent, REQ_IMAGE_EDIT);
            }

            @Override
            public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
                //图片编辑返回
                if (requestCode == REQ_IMAGE_EDIT && resultCode == RESULT_OK) {
                    if (ImageEditUtils.getInstance().getImageEditReturnInterface() != null)
                        ImageEditUtils.getInstance().getImageEditReturnInterface().editImageReturn(mImageFile);
                }
            }


        });
    }


    public static void onActivityResult(int requestCode, int resultCode, Intent data) {
        //图片选择返回
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            //获取拍摄的图片路径，如果是录制视频则是视频的第一帧图片路径
//            String captureImagePath = Matisse.obtainCaptureImageResult(data);
            //获取拍摄的视频路径
//            String captureVideoPath = Matisse.obtainCaptureVideoResult(data);
            //获取裁剪结果的路径，不管是选择照片裁剪还是拍摄照片裁剪，结果都从这里取
//            String cropPath = Matisse.obtainCropResult(data);


            String capturePath = null;
            String videoPath = null;
            String cropPath = null;
            if ((videoPath = Matisse.obtainCaptureVideoResult(data)) != null) {
                //录制的视频
//                capturePath = Matisse.obtainCaptureImageResult(data);
//                captureText.setText("视频路径：" + videoPath + " \n 第一帧图片：" + capturePath);
                if (emitterPrivate != null) {
                    emitterPrivate.onNext(videoPath);
                    LogUtil.d(videoPath);
                    emitterPrivate.onComplete();
                }
            } else if ((capturePath = Matisse.obtainCaptureImageResult(data)) != null) {
                //拍照返回
                if (emitterPrivate != null) {
                    emitterPrivate.onNext(capturePath);
                    LogUtil.d(capturePath);
                    emitterPrivate.onComplete();
                }
            } else if ((cropPath = Matisse.obtainCropResult(data)) != null) {
//                s += "\n 原图路径：" + Matisse.obtainSelectPathResult(data).get(0);
                //剪切返回
                if (emitterPrivate != null) {
                    emitterPrivate.onNext(cropPath);
                    LogUtil.d(cropPath);
                    emitterPrivate.onComplete();
                }
            } else {
                //图片路径 同样视频地址也是这个 根据requestCode
//            List<String> pathList = Matisse.obtainPathResult(data);
                List<String> pathList = Matisse.obtainSelectPathResult(data);
                if (pathList != null) {
                    if (emitterPrivate != null) {
                        for (String s : pathList) {
                            emitterPrivate.onNext(s);
                            LogUtil.d(s);
                        }
                        emitterPrivate.onComplete();
                        emitterPrivate = null;
                        LogUtil.d("图片选取完毕");
                    }
                }
            }
        }


    }


}
